import React, {Component} from "react";
import {ListView, Modal} from "antd-mobile";
import {restApiRequest} from "../Public/Api/Public";
import Login from "../Public/Components/Login";
import ico_expand_arrow from "../../images/ico_expand_arrow.png";
import pic_coupon_splitter from "../../images/pic_coupon_splitter.png";
import pic_empty_coupon from "../../images/pic_empty_coupon.png";
import PropTypes from "prop-types";

const alert = Modal.alert;

//页码
let pageNum = 0;
//每页显示数据的条数
const pageSize = 999;
let couponListUrl = '/shop/api/getUserCouponList';

export default class CouponPage extends Component {
    static contextTypes = {
        router: PropTypes.object
    }

    constructor(props, context) {
        super(props, context);
        this.state = {
            dataSource: new ListView.DataSource({
                rowHasChanged: (row1, row2) => row1 !== row2,
            }),
            visible: false,
            coupon_list: null
        };

    }

    componentWillMount() {
        //判断是否登录
        let sessionKey = localStorage.getItem('sessionkey');
        if (sessionKey === null) {
            this.setState({visible: true})
        } else {
            let param = {sessionkey: sessionKey, coupon_state: this.props.tabIndex};
            let jsonData = restApiRequest.getSign(param);
            this.fetchUserCouponList(couponListUrl, jsonData);
        }
    }

    //获取优惠券
    fetchUserCouponList(url, jsonData) {
        restApiRequest.fetchp(url, jsonData).then((response) => {
            if (!response.ok) {
                var error = new Error(response.statusText);
                error.response = response;
                throw error;
            } else {
                return response.json();
            }
        }).then((response_json) => {
            console.log(response_json.data);
            if (response_json.code == '0000' && response_json.data.length > 0) {
                this.setState({
                    dataSource: this.state.dataSource.cloneWithRows(response_json.data),
                    data: response_json.data
                });

            } else {
                this.setState({
                    coupon_list: response_json.data
                })

            }

        }).catch((ex) => {
            //ex.response.text().then((theText) => console.log(theText));
            console.log(ex);
        });

    }

    //点击跳转详情
    jumpRow(rowData) {
        // console.log(rowData)
        this.context.router.history.push({
            pathname: '/CouponProductList',
            search: rowData.coupon_id,
        })
    }


    format(time) {
        let da = new Date(parseInt(time) * 1000);
        let year = da.getFullYear() + '.';
        let month = da.getMonth() + 1 + '.';
        let date = da.getDate();
        return (year + month + date);
    }

    desc(rowID) {
        alert('使用说明', this.state.data[rowID].desc, [
            {text: '确定', onPress: () => console.log('cancel'), style: 'default'},
        ])
    }

    render() {

        const row = (rowData, sectionID, rowID) => {

            return (

                <div
                    className="coupon-item"
                >

                    <section className="coupon-item-left">

                        <section className="coupon-item-price">
                            <span>￥</span>
                            <span>{rowData.reduce_money}</span>
                        </section>

                        <section className="coupon-item-specifications">
                            {'满' + rowData.order_min_total_money + '元可使用'}
                        </section>

                    </section>

                    <img src={pic_coupon_splitter} className="coupon-item-line"/>

                    <section className="coupon-item-right">

                        <section className="coupon-item-title">
                            <p>{rowData.coupon_name}</p>
                            <p>{'可用时间：' + this.format(rowData.use_time_begin) + ' 至 ' + this.format(rowData.use_time_end)}</p>
                        </section>

                        <section className="coupon-item-btnwrap">
                            <button
                                className="coupon-item-btn"
                                onTouchStart={() => this.jumpRow(rowData)}
                                key={rowID}
                            >立即使用
                            </button>
                            <img src={ico_expand_arrow} className="coupon-item-arrow"
                                 onTouchStart={() => this.desc(rowID)}/>
                        </section>

                    </section>

                </div>

            )

        };

        const renderFooter = () => {

            return (
                <section className="hom-list-footer" style={{
                    paddingBottom: '.12rem'
                }}>
                    <p className="hom-list-footer-text">我是有底线的</p>
                    <svg className="hom-list-footer-icon">
                        <use xlinkHref={'#icon-ico_page_bottom_dog'}></use>
                    </svg>
                </section>
            )
        };

        const renderHeader = () => {

            return (
                <section className="order-list-top-placeholder"/>
            )
        };

        return (
            <div>
                {this.state.visible ? <Login onClosedCallback={
                    () => {
                        this.setState({visible: false});
                    }
                }/> : null}

                {
                    this.state.coupon_list ?
                        <div className="coupon-null-img">
                            <img src={pic_empty_coupon}/>
                        </div> :
                        <ListView
                            dataSource={this.state.dataSource}
                            renderRow={row}
                            renderHeader={renderHeader}
                            renderFooter={renderFooter}
                            style={{
                                height: window.innerHeight - 95,
                            }}
                        />

                }
            </div>
        )
    }
}
